<?php

namespace Home\Controller;

use Think\Controller;

class BaseController extends Controller {

    private $UserToken;

    public function __construct() {
        //入口文件
        $data = I('param.');

        //不做效验的接口地址
        $allowURL = Array(
            'User.UserInfoAction',
            'User.getStations',
            'Callback.ztRegisterCallback',
            'Common.sendVerifyCode',
            'Common.queryWeinxin',
            'Common.openSendSms',
            'Common.sendVerify',
            'Common.queryLatestVersionInfo',
            'Common.queryLatestVersionList',
            'Common.getAddressWithStationId',
            'StationInfo.modifyPassword',
            'Pay.payCallBack',
            'User.register',
            'User.courierRegister',
            'Order.queryDeliveryCompany',
            'Order.queryDeliveryCompanyGroup',
            'Order.setPackageNoticed',
            'Order.setSmsNoticed',
            'Pay.mailPayCallPack'
        );

        //file_put_contents('1.txt', json_encode($data) . "\n", FILE_APPEND);
        //验签
        if (!in_array($data['reqUrl'], $allowURL) && isset($_GET['buildVersion']) && intval($_GET['buildVersion']) >= 22 && !$this->getSignDecode($data)) {
            $this->auto_error('验证失败! 请重新登录!'); // . $this ->getDataString( $data ) . '  -  ' . $this ->UserToken
        }
    }

    /**
     * @desc: 统一输出接口
     * @Author: delayhsiao
     * @update: 2016-11-21
     * */
    public function output($status, $data = null ,$msg = '') {
        if ($status) {
            $return = array(
                'a' => 0,
                'm' => empty($msg) ? '请求成功' : $msg,
                'success' => true,
                'e' => '0',
                'd' => $data
            );
        } else {
            $return = array(
                'a' => 1,
                'm' => empty($msg) ? '操作失败' : $msg,
                'success' => false,
                'e' => '-1000010104',
                'd' => array('success' => '1')
            );
        }
        $this->ajaxReturn($return);
    }

    /**
     * @desc: 自定义报错接口
     * @Author: delayhsiao
     * @update: 2016-11-26
     * */
    public function auto_error($info) {
        $return = array(
            'a' => 1,
            'm' => $info,
            'success' => false,
            'e' => '-1000010104',
            'd' => null
        );
        $this->ajaxReturn($return);
    }

    /**
     * @desc: 参数校验错误输出
     * @Author: delayhsiao
     * @update: 2016-11-21
     * */
    public function param_error() {
        $return = array(
            'a' => 1,
            'm' => '参数校验错误',
            'success' => false,
            'e' => '-1000010102',
            'd' => null
        );
        $this->ajaxReturn($return);
    }

    /**
     * * 接口入口方法
     * * author:delayhsiao
     * * date:2016年10月13日
     * */
//	public function signature( $data )
//    {
//		unset($data['sign']);
//		ksort($data);
//		foreach($data as $k => $v){
//			$str = $k.$v;
//		}
//		$signature_str = C('signature');
//		$sign = md5($signature_str.$str);
//		return strtoupper($sign);
//	}

    /**
     * Function getSignDecode
     * @param array $data
     * @return bool
     *
     * Author: 黄盖
     * Date: 2017-3-10 13:49
     * Info: 验证sign是否合法
     */
    private function getSignDecode($data = Array()) {
        //sign 由 uid + md5( pwd + key1 + val1 + key2 + val2 ... ) 组成
        if (isset($data['sign']) && strlen($data['sign']) > 32) {
            $token = substr($data['sign'], -32);
            $uid = substr($data['sign'], 0, -32);

            //验证
            return $this->SignVerify($uid, $token, $this->getDataString($data));
        }

        return false;
    }

    /**
     * Function SignVerify
     * @param $uid
     * @param $token
     * @param string $dataSTR
     * @return bool
     *
     * Author: 黄盖
     * Date: 2017-3-10 14:07
     * Info: 获取用户密码， 加密后 与 sign对比
     */
    private function SignVerify($uid, $token, $dataSTR = '') {
        //获取用户密码
        $pwd = $this->getUserPWD($uid);

        if (!empty($pwd)) {
            //本地加密结果
            $this->UserToken = md5($pwd . $dataSTR);

            if ($this->UserToken == $token) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * Function getDataString
     * @param $data
     * @return string
     *
     * Author: 黄盖
     * Date: 2017-3-10 15:02
     * Info: 获取参数
     */
    private function getDataString($data) {
        unset($data['sign']);
        unset($data['bmxVersion']);
        unset($data['bmxSource']);
        unset($data['buildVersion']);
        unset($data['professional']);
        ksort($data);
        $str = '';

        foreach ($data as $k => $v) {
            $str .= $k . htmlspecialchars_decode($v);
        }

        return $str;
    }

    /**
     * Function getUserPWD
     * @param $uid
     * @return bool
     *
     * Author: 黄盖
     * Date: 2017-3-10 15:14
     * Info: 获取用户密码
     */
    private function getUserPWD($uid) {
        $user_info = ( new \Home\Model\UserModel())->getUserInfo($uid);

        //如果用户存在, 且未被禁用
        if (isset($user_info['f_user_pwd']) && $user_info['f_user_status'] == 1) {
            return $user_info['f_user_pwd'];
        }

        return false;
    }

    /**
     * @desc: 雅居乐需要返回的数据格式
     * @Author: cheng
     * @update: 2017-06-22
     * */
    public function yjlOutPut($status, $data = null) {
        if ($status) {
            $return = array(
                'code' => 0,
                'msg_cn' => '请求成功',
                'msg_en' => 'success',
                'data' => $data
            );
        } else {
            $return = array(
                'code' => 1,
                'msg_cn' => '操作失败',
                'msg_en' => 'unsuccess',
                'data' => array()
            );
        }
        $this->ajaxReturn($return);
    }
    
    /**
     * @desc: 参数校验错误输出（雅居乐需要返回的数据格式）
     * @Author: cheng
     * @update: 2017-06-22
     * */
    public function yjlParamError($info = '') {
        $return = array(
                'code' => 1,
                'msg_cn' => empty($info) ? '参数校验错误' : $info,
                'msg_en' => 'unsuccess',
                'data' => array()
            );
        $this->ajaxReturn($return);
    }

}
